<template>
  <div class='container'>
    <!-- 试题录入模块 -->
    <el-card class="box-card" ref="cardRef">
    <!-- 卡片视图的头部区域 -->
      <div slot="header">
        <span>试题录入</span>
      </div>
    <!-- /卡片视图的头部区域 -->
    <!-- 卡片视图的主体区域 -->
      <!-- 录入新试题的表单 newQuestionsFormRef -->
      <el-form ref="newQuestionsFormRef" :model="newQuestionsForm" :rules="newQuestionsFormRules">
        <!-- 选择框区域 -->
        <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="newQuestionsForm.subjectID" placeholder="请选择" @change="selectedSubjectChange($event)">
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="newQuestionsForm.catalogID" placeholder="请选择">
              <el-option
                v-for="(item, index) in menuList"
                :key="index"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="newQuestionsForm.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
            <el-select v-model="newQuestionsForm.province" placeholder="请选择" style="width: 198px" @change="selectCityChange($event)">
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select v-model="newQuestionsForm.city" placeholder="请选择" style="width: 198px; margin-left: 4px">
              <el-option
                v-for="(item, index) in regionList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
            <el-select v-model="newQuestionsForm.direction" placeholder="请选择">
              <el-option
                v-for="(item, index) in fieldList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- /选择框区域 -->
        <!-- 单选区域 -->
        <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="newQuestionsForm.questionType">
              <el-radio
                v-for="(item, index) in questionTypeList"
                :key="index"
                :label="item.value"
                name="questionType"
              >{{item.label}}
              </el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="newQuestionsForm.difficulty">
              <el-radio
                v-for="(item, index) in difficultyList"
                :key="index"
                :label="item.value"
                name="difficulty"
              >{{item.label}}
              </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- /单选区域 -->
        <!-- 题干所使用的 富文本编辑器 -->
        <el-form-item label="题干：" prop="question">
            <quill-editor
              ref="quillEditorRef"
              v-model="newQuestionsForm.question"
              :options="quillEditorOption"
              @change="firstEditorChange()"
              ></quill-editor>
        </el-form-item>
        <!-- /题干所使用的 富文本编辑器 -->
        <!-- 题目选项区域 -->
        <el-form-item label="选项：" v-show="newQuestionsForm.questionType === 1 || newQuestionsForm.questionType === 2">
          <!-- 题目选项为单选时 -->
          <!-- ***用 v-show 代替 v-if ，优化性能 -->
          <div v-show="newQuestionsForm.questionType === 1">
            <div v-for="(item, index) in newQuestionsForm.options" :key="index" class="radio_option_item">
              <el-radio
                v-model="radioSelection3"
                :label="item.code"
                @change="handleRadioChange(item)"
              >
              </el-radio>
              <el-input v-model="item.title"></el-input>
              <!-- 注意：action 为必选参数，其值是图片上传的地址 -->
              <el-upload
                class="img-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="uploadImg"
                :before-upload="beforeUploadImg"
              >
                <img v-if="imageUrl" :src="index === imageId ? imageUrl : ''" class="avatar" />
                <span @click="handleImgId(index)">上传图片</span>
                <i class="el-icon-circle-close img-uploader-icon" @click="deleteImg(index)"></i>
              </el-upload>
            </div>
          </div>
          <!-- 题目选项为多选时 -->
          <div v-show="newQuestionsForm.questionType === 2">
            <div v-for="(item, index) in newQuestionsForm.options" :key="index" class="checkbox_option_item">
              <el-checkbox
                v-model="item.isRight"
                :label="true"
              >{{ item.code }}
              </el-checkbox>
              <el-input v-model="item.text"></el-input>
              <el-upload
                class="img-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-success="uploadImg"
                :before-upload="beforeUploadImg"
              >
                <img v-if="imageUrl" :src="index === imageId ? imageUrl : ''" class="avatarImg" />
                <span @click="handleImgId(index)">上传图片</span>
                <i class="el-icon-circle-close img-uploader-icon" @click="deleteImg(index)"></i>
              </el-upload>
          </div>
          </div>
          <!-- 增加选项与答案的按钮 -->
          <el-button
            v-show="newQuestionsForm.questionType !== 3"
            type="danger"
            size="mini"
            :disabled="isAddSelectionBtndisabled"
            @click="addCheckboxOption"
          >+ 增加选项与答案</el-button>
        </el-form-item>
        <!-- /题目选项区域 -->
        <!-- 解析视频区域 -->
        <el-form-item label="解析视频：">
          <el-input  v-model="newQuestionsForm.videoURL"></el-input>
        </el-form-item>
        <!-- /解析视频区域 -->
        <!-- 答案解析所使用的 富文本编辑器 -->
        <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              ref="quillEditorRef"
              v-model="newQuestionsForm.answer"
              :options="quillEditorOption"
              @change="secondEditorChange($event)"
              ></quill-editor>
        </el-form-item>
        <!-- /答案解析所使用的 富文本编辑器 -->
        <!-- 题目备注区域 -->
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            :rows="4"
            v-model="textarea"
          ></el-input>
        </el-form-item>
        <!-- /题目备注区域 -->
        <!-- 试题标签区域 -->
        <el-form-item label="试题标签：">
            <el-select v-model="newQuestionsForm.tags" placeholder="请选择试题标签">
              <el-option
                v-for="(item, index) in tagList"
                :key="index"
                :label="item.tagName"
                :value="item.tagName"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- /试题标签区域 -->
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button :type="!this.$route.query.id ? 'primary' : 'success'" @click="onSubmit">{{ !this.$route.query.id ? '确认提交' : '确认修改'}}</el-button>
        </el-form-item>
        <!-- /提交按钮 -->
      </el-form>
      <!-- /录入新试题的表单 newQuestionsFormRef -->
    <!-- /卡片视图的主体区域 -->
    </el-card>
  </div>
</template>

<script>
// 在此文件内局部导入 富文本编辑器 第三方包
import { quillEditor } from 'vue-quill-editor'

// 导入 富文本编辑器 的样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 从 存储着城市列表数据的 js文件 引入数据
// 从 存储着方向列表数据，题目难度和题型数据的 js文件 引入数据
// 从 定义了请求学科简单列表数据方法的 js文件 引入请求
// 从 定义了请求目录列表数据方法的 js文件 引入请求
// 从 定义了请求标签列表数据方法的 js文件 引入请求
import { provinces, citys } from '../../api/hmmm/citys'
import { direction, difficulty, questionType } from '../../api/hmmm/constants.js'
import { list as xuekeList } from '../../api/hmmm/subjects'
import { list as gongsilist } from '../../api/hmmm/companys'
import { list as muluList } from '@/api/hmmm/directorys'
import { list as biaoqianList } from '@/api/hmmm/tags'

// 导入 添加基础题库 的请求
import { add, detail as questionDetail, update } from '@/api/hmmm/questions'

export default {
  name: 'questionNew',
  components: {
    quillEditor
  },
  mounted () {
    this.loadData()
    if (this.$route.query.id) {
      this.getQuestionList()
    }
    // console.log(this.$route.query.id)
  },
  computed: {
    isAddSelectionBtndisabled () {
      if (this.newQuestionsForm.questionType !== 2) {
        return true
      } else {
        return false
      }
    }
  },
  data () {
    return {
      subjectList: [],
      menuList: [],
      companyList: [],
      cityList: [],
      regionList: [],
      fieldList: [],
      difficultyList: [],
      questionTypeList: [],
      tagList: [],
      radioSelection3: '',
      startCode: 68,
      imageUrl: '',
      imageId: '',
      // 录入新试题的表单对象
      newQuestionsForm: {
        subjectID: '',
        // 目录ID
        catalogID: '',
        enterpriseID: '',
        // province: '',
        city: '',
        direction: '',
        difficulty: 1,
        questionType: 1,
        // 题干
        // question: '',
        // 答案解析
        // answer: '',
        // 标签
        tags: '',
        options: [
          { code: 'A:', text: '', img: '', isRight: false, title: '' },
          { code: 'B:', text: '', img: '', isRight: false, title: '' },
          { code: 'C:', text: '', img: '', isRight: false, title: '' },
          { code: 'D:', text: '', img: '', isRight: false, title: '' }
        ],
        videoURL: ''
        /* remarks: null,
        videoURL: null */
        /* delivery: false,
        radioSelection: [],
        resource: '',
        desc: '' */
      },
      // 录入新试题表单 的验证规则对象
      newQuestionsFormRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型' }
        ],
        difficulty: [
          { required: true, message: '请选择难度' }
        ],
        question: [
          { required: true, message: '请输入题干' }
        ],
        answer: [
          { required: true, message: '请输入答案解析' }
        ]
      },
      quillEditorOption: {
        modules: {
          toolbar: [
            // 加粗，斜体，下划线，删除线
            ['bold', 'italic', 'underline', 'strike'],
            // 列表排序方式
            [{ list: 'ordered' }, { list: 'bullet' }],
            // 引用
            ['blockquote'],
            // 代码块，上传图片
            ['code-block', 'image', 'link']
          ]
        },
        placeholder: ''
      },
      textarea: ''
    }
  },
  methods: {
    // 动态渲染 选择框和单选框 中的数据
    async loadData () {
      // console.log(direction)
      this.fieldList = direction
      // console.log(difficulty)
      this.difficultyList = difficulty
      // console.log(questionType)
      this.questionTypeList = questionType
      this.cityList = provinces()
      const res1 = await xuekeList()
      // console.log(res1)
      // 包含所有学科数据的数组
      this.subjectList = res1.data.items
      // console.log(res.data.items)
      // 包含所有企业的所有数据的数组，其中包括企业ID和企业名等数据
      const res2 = await gongsilist()
      this.companyList = res2.data.items
      // console.log(this.cityList)
      // 包含所有城市数据的数组
      /* this.cityList.forEach(cityname => {
        console.log(citys(cityname))
        // 遍历包含城区数据的所有数组
      }) */
    },
    // ******重难点：判断 单选框中每个选项 是否被选中，给 单选框中每个选项对象的 isRight 属性赋值，将 每个选项是否被选中的状态 保存下来，便于后续修改题目时使用
    handleRadioChange () {
      this.newQuestionsForm.options.forEach(item => {
        if (item.code === this.radioSelection3) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // ******注意：目录选择框 和 试题标签选择框 中的数据只有在 学科选择框 中的内容发生变化时才会被渲染出来
    // 监听 学科选择框 的变化事件，然后渲染 学科目录列表 下的 二级列表(目录列表和试题标签)
    async selectedSubjectChange (value) {
      // console.log(value)
      try {
        // 将请求到的 标签列表数据 存储到 tagList 数组中
        const res = await biaoqianList({ subjectID: value })
        // console.log(res.data.items)
        this.tagList = res.data.items
        // 二级目录 this.subjectSelect.value
        const { data } = await muluList({ subjectID: value })
        this.menuList = data.items
        // console.log(this.menuList)
      } catch (err) {
        console.log(err)
      }
    },
    // 监听 城市选择框中内容 的变化事件
    selectCityChange (selectedCity) {
      // console.log(selectedCity)
      // 通过传参拿到 当前被选中的城市，将 当前城市的城区数组 赋值给 regionList
      this.regionList = citys(selectedCity)
    },
    // 监听 图片上传 事件
    uploadImg (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeUploadImg (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleImgId (imgId) {
      this.imageId = imgId
    },
    // 监听 增加选项与答案按钮 的点击事件
    addCheckboxOption () {
      this.subCode()
      // console.log(this.startCode)
      this.newQuestionsForm.options.push({
        code: `${String.fromCharCode(this.startCode)}:`,
        title: '',
        img: '',
        isRight: ''
      })
    },
    // ***给 选项的字母 所对应的 ASCII码值 增加 一位
    subCode () {
      this.startCode += 1
    },
    // 监听 富文本编辑器中内容 的改变事件
    firstEditorChange () {},
    secondEditorChange () {},
    // 监听 确认提交按钮 的点击事件
    onSubmit () {
      this.$refs.newQuestionsFormRef.validate(async valid => {
        if (valid) {
          // console.log(this.newQuestionsForm)
          // 发起 添加基础题库 的请求
          try {
            // ******判断 是提交新题目还是修改题目
            if (!this.$route.query.id) {
              // this.newQuestionsForm.subjectID += ''
              this.newQuestionsForm.questionType += ''
              this.newQuestionsForm.difficulty += ''
              await add(this.newQuestionsForm)
              this.$router.push('/questions/list')
              this.$message.success('试题录入成功！')
            } else {
              this.newQuestionsForm.remarks = this.textarea
              this.newQuestionsForm.questionType += ''
              this.newQuestionsForm.difficulty += ''
              console.log(this.newQuestionsForm)
              update(this.newQuestionsForm)
              this.$router.push('/questions/list')
              this.$message.success('试题修改成功！')
            }
          } catch (err) {
            console.log(err)
            this.$message.success('操作失败，请稍后重试！')
          }
        } else {
          // 表单预校验
          return this.$message.error('试题录入失败，请填写完整的试题信息！')
        }
      })
    },
    // 修改基础题库 获取数据
    async getQuestionList () {
      // console.log(this.$route.query.id)
      const { data } = await questionDetail({ id: this.$route.query.id })
      console.log(data)
      data.options.forEach(item => {
        if (item.isRight === 1) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      this.newQuestionsForm = data
      // console.log(data.subjectID)
      this.newQuestionsForm.questionType = data.questionType - 0
      this.newQuestionsForm.difficulty = data.difficulty - 0
      this.selectedSubjectChange(data.subjectID)
      this.handleDefaultRadio(data.options)
      this.textarea = data.remarks
    },
    // ******重难点：获取到 需要修改的旧题目数据 后，根据 isRight的值 挨个判断 所获取到的数据里的选项 是否被选中，将 被选中项的code值 赋值给 el-radio的v-model 属性，把被选中项显示出来
    handleDefaultRadio (arr) {
      arr.some(item => {
        if (item.isRight) {
          this.radioSelection3 = item.code
          return true
        }
      })
    },
    deleteImg (imageId) {
      if (imageId === this.imageId) {
        this.imageUrl = ''
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 20px;
}
.el-card {
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  transition: 0.3s;
}
.el-form-item {
  margin-bottom: 22px;
  // 注：::v-deep —— SASS语法中用于样式穿透的深度选择器
   ::v-deep .el-form-item__label {
    width: 120px;
    float: left;
    text-align: right;
    vertical-align: middle;
    box-sizing: border-box;
    padding: 0 12px 0 0;
    color: #606266;
    font-size: 14px;
  }
   ::v-deep .el-form-item__content {
    line-height: 36px;
    margin-left: 120px;
     ::v-deep label {
      width: 120px;
    }
    .radio_option_item {
      padding-bottom: 20px;
      .el-input {
        width: 240px;
      }
      label {
        margin-right: 8px;
      }
      .el-input {
        width: 240px;
      }
      .img-uploader {
        display: inline-block;
        vertical-align: middle;
        line-height: 1;
        .el-upload {
          position: relative;
          width: 100px;
          height: 60px;
          line-height: 60px;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          margin-left: 6px;
          .img-uploader-icon {
            position: absolute;
            right: 0;
            top: 0;
            -webkit-transform: translate(50%,-50%);
            transform: translate(50%,-50%);
            background: #fff;
            font-size: 18px;
            color: #999;
          }
        }
        .el-upload:hover {
          border: 1px dashed #01c6fa;
        }
      }
    }
  }
  .checkbox_option_item {
      height: 50px;
      margin-bottom: 30px;
      .el-input {
        width: 240px;
      }
      label {
        margin-right: 8px;
      }
       ::v-deep .img-uploader {
        display: inline-block;
        vertical-align: middle;
        line-height: 1;
        .el-upload {
          position: relative;
          width: 100px;
          height: 60px;
          line-height: 60px;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          margin-left: 6px;
          .img-uploader-icon {
            position: absolute;
            right: 0;
            top: 0;
            -webkit-transform: translate(50%,-50%);
            transform: translate(50%,-50%);
            background: #fff;
            font-size: 18px;
            color: #999;
          }
        }
        .el-upload:hover {
          border: 1px dashed #01c6fa;
        }
      }
    }
  .quill-editor {
     ::v-deep .ql-toolbar {
      padding: 0 8px
    }
     ::v-deep .ql-editor {
       height: 200px;
     }
  }
}

.el-select {
  width: 400px;
}

.el-input {
  width: 400px;
}

.el-textarea {
  width: 400px;
}
</style>
